package com.chuanye.mydrawable.activitys;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;

import com.chuanye.mydrawable.R;
import com.chuanye.mydrawable.adapters.DepManExpandAdapter;
import com.chuanye.mydrawable.adapters.FaultTypeAdapter;
import com.chuanye.mydrawable.adapters.MaintainAdapter;
import com.chuanye.mydrawable.adapters.PersonnelAdapter;
import com.chuanye.mydrawable.adapters.ProInfoAdapter;
import com.chuanye.mydrawable.adapters.RecyPersonnelAdapter;
import com.chuanye.mydrawable.adapters.RecySupUserAdapter;
import com.chuanye.mydrawable.adapters.RecyclerViewAdapter;
import com.chuanye.mydrawable.adapters.RereConAdapter;
import com.chuanye.mydrawable.adapters.SupportAdapter;
import com.chuanye.mydrawable.adapters.SupportUserOneAdapter;
import com.chuanye.mydrawable.beans.MaintainBean;
import com.chuanye.mydrawable.beans.ProInfoBean;
import com.chuanye.mydrawable.beans.RemoteListBean;
import com.chuanye.mydrawable.beans.RepairInfoBean;
import com.chuanye.mydrawable.beans.SupportBean;
import com.chuanye.mydrawable.beans.SupportUserBean;
import com.chuanye.mydrawable.beans.UserBean;
import com.chuanye.mydrawable.json.LocalJson;
import com.chuanye.mydrawable.utils.DateUtils;
import com.chuanye.mydrawable.utils.HttpUtils;
import com.chuanye.mydrawable.views.DateDialog;
import com.chuanye.mydrawable.views.SpaceItemDecoration;
import com.chuanye.mydrawable.views.TimeDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class RemoteActivity extends AppCompatActivity implements View.OnClickListener{

   /* GetSupportUser 点击远程部门加载对应人员 远程部门GetSupport
    GetProInfo获取项目及保质期
    人员 let AcceptanceUserPara = { RoleID: 60 }; //60 User获取人员*/

    private TextView crreremot_number_tv;
    private TextView crreremot_maintain_tv;
    private EditText crreremot_servicesupport_et;
    private TextView crreremot_project_tv;
    private TextView crreremot_guaranteedate_tv;
    private RadioGroup crreremot_arrange_rg;
    private RadioButton crreremot_arrange_rb_no;
    private RadioButton crreremot_arrange_rb_go;
    private CheckBox crreremot_feedback_ck;
    private TextView crreremot_starttime_tv;
    private TextView crreremot_stoptime_tv;
    private EditText crreremot_car_et;
    private EditText crreremot_remark_et;
    private Button crreremot_save_btn;
    private Button crreremot_submit_btn;
    private Button crreremot_end_btn;

    private Context mContext;
    public long startTime = System.currentTimeMillis();
    public long endTime = System.currentTimeMillis();

    //人员集合
    private List<UserBean.ListBean> userlist = new ArrayList<>();
    public static List<UserBean.ListBean> userlist2 = new ArrayList<>();
    HashMap<Integer,Boolean> userisselected = new HashMap<Integer,Boolean>();//记录部门是否选中

    //远程外部  部门 集合
    private List<SupportBean.ObjBean> supportList = new ArrayList<>();
    public static List<SupportBean.ObjBean> supportList2 = new ArrayList<>();
    HashMap<Integer,Boolean> isselected = new HashMap<Integer,Boolean>();//记录部门是否选中
    //远程外部 人员 集合
    private List<SupportUserBean.ObjBean> supportuserList = new ArrayList<>();
    public static List<SupportUserBean.ObjBean.ValueBean> valueBeanList = new ArrayList<>();
    HashMap<String,Boolean> supportuserisselected = new HashMap<String,Boolean>();//记录外部人员是否选中
    private List<SupportUserBean.ObjBean> RemotePeopleList = new ArrayList<>();//远程外部 人员 回显集合
    private List<SupportUserBean.ObjBean> SpotPeopleList = new ArrayList<>();//远程外部 人员 回显集合

    //维修换新集合
    private List<MaintainBean> maintainList = new ArrayList<>();
    //项目集合
    private List<ProInfoBean.ObjBean> proinfoList = new ArrayList<>();
    private LinearLayout crreremot_remoteexternal_ll;
    //远程外部 部门
    public static TextView crreremot_remoteexternal_tv;
    public static RecyclerView crreremot_remoteexternal_rv;
    public static RecyclerViewAdapter recyclerViewAdapter;
    private ImageView crreremot_pulldown_iv;

    //远程外部 人员
    public static TextView crreremot_departmentman_tv;
    private LinearLayout crreremot_departmentman_ll;
    private ImageView crreremot_departmentman_iv;
    public static RecyclerView crreremot_departmentman_rv;
    public static RecySupUserAdapter recySupUserAdapter;
    //隐藏的布局
    private LinearLayout remote_ll;

    //人员
    public static TextView crreremot_man_tv;
    private LinearLayout crreremot_man_ll;
    public static RecyclerView crreremot_man_rv;
    public static RecyPersonnelAdapter recyPersonnelAdapter;
    private ImageView crreremot_man_iv;
    //现场外部 人员
    public static TextView crreremot_departmentmango_tv;
    private LinearLayout crreremot_departmentmango_ll;
    public static RecyclerView crreremot_departmentmango_rv;
    public static RecySupUserAdapter departmentmangoAdapter;
    private ImageView crreremot_departmentmango_iv;
    public static List<SupportUserBean.ObjBean.ValueBean> departmentmango_valueBeanList = new ArrayList<>();
    HashMap<String,Boolean> departmentmango_isselected = new HashMap<String,Boolean>();//记录外部人员是否选中
    //现场外部 部门
    public static TextView crreremot_spotexternal_tv;
    private LinearLayout crreremot_spotexternal_ll;
    public static RecyclerView crreremot_spotexternal_rv;
    public static RecyclerViewAdapter spotexternalAdapter;
    private ImageView crreremot_spotexternal_iv;
    public static List<SupportBean.ObjBean> spotexternal = new ArrayList<>();
    HashMap<Integer,Boolean> spotexternal_isselected = new HashMap<Integer,Boolean>();//记录部门是否选中
    private int maintainId;//维修换新ID
    private String projectId;//项目ID
    private String projectGuid;
    private  int arrange = 2;//1去现场 2不去现场
    private String feedback = "1";//1已以告知报修人安排和费用确认2已处理
    private String nextOperatorID;
    private String warrantyTime1;//项目时间


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remote);
        mContext = this;
        //初始化控件
        initView();


        initData();
        getremoteList();

    }

    private void getremoteList() {
        OkHttpUtils.post()
                .url("http://172.16.2.77:9001/api/RepairProcess/GetRemoteList")//获取远程集合
                .addParams("Step", "2")
                .addParams("RepairId", "20190219-京-HD-0013")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(okhttp3.Call call, Exception e, int id) {
                        Log.i("获取远程编辑请求异常：",e.toString());

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("获取远程编辑请求数据：",response.toString());
                        Gson gson = new Gson();
                        String str = response.toString();
                        RemoteListBean remotelistbean = gson.fromJson(str,RemoteListBean.class);
                        List<RemoteListBean.ListBean> list = remotelistbean.getList();
                        if (list!= null && list.size() > 0){
                            RemoteListBean.ListBean listBean = list.get(0);

                            //报修编号：
                            if (!TextUtils.isEmpty(listBean.getRepairId())){
                                crreremot_number_tv.setText(listBean.getRepairId());
                            }

                            //远程外部 部门
                            String SupportIDs = listBean.getSupportIDs();
                            String SupportNames = listBean.getSupportNames();
                            String [] strIds =SupportIDs.split(",");
                            String [] strNames =SupportNames.split(",");
                            for (int i = 0; i < strIds.length; i++){
                                SupportBean.ObjBean objBean = new SupportBean.ObjBean();
                                objBean.setSupportId(Integer.valueOf(strIds[i]));
                                objBean.setSupportName(strNames[i]);
                                supportList2.add(objBean);
                            }
                            crreremot_remoteexternal_tv.setVisibility(View.GONE);
                            crreremot_remoteexternal_rv.setVisibility(View.VISIBLE);
                            recyclerViewAdapter.notifyDataSetChanged();


                            //维修和换新 1维修2换新3修和换 0无
                            if (listBean.getRepairOrChange() == 0){
                                crreremot_maintain_tv.setText("无");
                                maintainId = 0;
                            }else if (listBean.getRepairOrChange() == 1) {
                                crreremot_maintain_tv.setText("维修");
                                maintainId = 1;
                            }else if (listBean.getRepairOrChange() == 2) {
                                crreremot_maintain_tv.setText("换新");
                                maintainId = 2;
                            } else if (listBean.getRepairOrChange() == 3) {
                                crreremot_maintain_tv.setText("维修和换新");
                                maintainId = 3;
                            }

                            //远程外部 人员
                            String SupportUserIDs = listBean.getSupportUserIDs();
                            String SupportUserNames = listBean.getSupportUserNames();
                            try {
                                GetSupportUser(1,true,SupportUserIDs);//1为远程外部人员  true为回显
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                            //服务支持
                            if (!TextUtils.isEmpty(listBean.getDescribe())){
                                crreremot_servicesupport_et.setText(listBean.getDescribe());
                            }

                            //项目
                            crreremot_project_tv.setText(listBean.getProjectName());
                            //质保期
                            crreremot_guaranteedate_tv.setText(listBean.getWarrantyTime().subSequence(0,10)+" 00-00");
                            warrantyTime1 = listBean.getWarrantyTime().subSequence(0,10)+" 00-00";

                            //服务安排
                            if (listBean.getFixUp() == 1){//去现场
                                crreremot_arrange_rb_go.setChecked(true);
                                arrange = 1;
                            }else if (listBean.getFixUp() == 2){//不去现场
                                arrange = 2;
                                crreremot_arrange_rb_no.setChecked(true);
                            }
                            //反馈
                            if (listBean.getFeedback() == 1){
                                crreremot_feedback_ck.setChecked(true);
                                feedback = "1";
                            }else {
                                crreremot_feedback_ck.setChecked(false);
                                feedback = "2";
                            }

                            //时间
                            if (!TextUtils.isEmpty(listBean.getSceneTime())){
                                //开始时间
                                String starttime = listBean.getSceneTime().replace("T"," ").substring(0,16);
                                crreremot_starttime_tv.setText(starttime);
                            }
                            if (!TextUtils.isEmpty(listBean.getEndTime())){
                                //截止时间
                                String endtime = listBean.getEndTime().replace("T"," ").substring(0,16);
                                crreremot_stoptime_tv.setText(endtime);
                            }

                            //车辆
                            if (!TextUtils.isEmpty(listBean.getPlateNumber())){
                                crreremot_car_et.setText(listBean.getPlateNumber());
                            }

                            //人员
                            String userIDs = listBean.getUserIDs();
                            String [] struserIDs =userIDs.split(",");
                            for (int i = 0; i < struserIDs.length; i++){
                               for (int n = 0; n < userlist.size(); n++){
                                   if (Integer.valueOf(struserIDs[i]) == userlist.get(n).getUserID()){
                                       UserBean.ListBean listBean1 = new UserBean.ListBean();
                                       listBean1.setUserID(userlist.get(n).getUserID());
                                       listBean1.setUserName(userlist.get(n).getUserName());
                                       userlist2.add(listBean1);
                                   }
                               }
                            }
                            crreremot_man_tv.setVisibility(View.GONE);
                            crreremot_man_rv.setVisibility(View.VISIBLE);
                            recyPersonnelAdapter.notifyDataSetChanged();

                            //现场外部 部门
                            String Scene_SupportIDs = listBean.getScene_SupportIDs();
                            String Scene_SupportNames = listBean.getScene_SupportNames();
                            String [] strSceneIds =Scene_SupportIDs.split(",");
                            String [] strSceneNames =Scene_SupportNames.split(",");
                            for (int i = 0; i < strSceneIds.length; i++){
                                SupportBean.ObjBean objBean = new SupportBean.ObjBean();
                                objBean.setSupportId(Integer.valueOf(strSceneIds[i]));
                                objBean.setSupportName(strSceneNames[i]);
                                spotexternal.add(objBean);
                            }
                            crreremot_spotexternal_tv.setVisibility(View.GONE);
                            crreremot_spotexternal_rv.setVisibility(View.VISIBLE);
                            spotexternalAdapter.notifyDataSetChanged();

                            //现场外部 人员
                            String Scene_SupportUserIDs = listBean.getScene_SupportUserIDs();
                            String Scene_SupportUserNames = listBean.getScene_SupportUserNames();
                            try {
                                GetSupportUser(2,true,Scene_SupportUserIDs);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                            //备注
                            if (!TextUtils.isEmpty(listBean.getRemark())){
                                crreremot_remark_et.setText(listBean.getRemark());
                            }
                        }


                    }
                });
    }

    /**
     * 初始化数据
     */
    private void initData() {
        //维修换新集合
        String maintainAndrenew = LocalJson.maintainAndrenew;
        Gson gson = new Gson();
        maintainList = gson.fromJson(maintainAndrenew, new TypeToken<ArrayList<MaintainBean>>(){}.getType());
        //获取部门集合
        GetSupport();
        //获取项目集合
        getProInfo();
        //人员
        getUser();
        //远程外部 部门
        recyclerViewAdapter = new RecyclerViewAdapter(supportList2,this);
        crreremot_remoteexternal_rv.setAdapter(recyclerViewAdapter);
        //删除数据
        recyclerViewAdapter.setOnDeleteIconClickListener(new RecyclerViewAdapter.OnDeleteIconClickListener() {
            @Override
            public void onDeleteIconClick(int pos) {
                recyclerViewAdapter.removeData(pos);
            }
        });

        // 远程外部  人员
        recySupUserAdapter = new RecySupUserAdapter(valueBeanList,this);
        crreremot_departmentman_rv.setAdapter(recySupUserAdapter);
        //删除数据
        recySupUserAdapter.setOnDeleteIconClickListener(new RecySupUserAdapter.OnDeleteIconClickListener() {
            @Override
            public void onDeleteIconClick(int pos) {
                recySupUserAdapter.removeData(pos);
            }
        });

        //人员
        recyPersonnelAdapter = new RecyPersonnelAdapter(mContext,userlist2);
        crreremot_man_rv.setAdapter(recyPersonnelAdapter);
        //删除数据
        recyPersonnelAdapter.setOnDeleteIconClickListener(new RecyPersonnelAdapter.OnDeleteIconClickListener() {
            @Override
            public void onDeleteIconClick(int pos) {
                recyPersonnelAdapter.removeData(pos);
            }
        });

        //现场外部  部门
        spotexternalAdapter = new RecyclerViewAdapter(spotexternal,this);
        crreremot_spotexternal_rv.setAdapter(spotexternalAdapter);
        //删除数据
        spotexternalAdapter.setOnDeleteIconClickListener(new RecyclerViewAdapter.OnDeleteIconClickListener() {
            @Override
            public void onDeleteIconClick(int pos) {

                spotexternalAdapter.removeData(pos);
            }
        });

        //现场外部 人员
        departmentmangoAdapter = new RecySupUserAdapter(departmentmango_valueBeanList,this);
        crreremot_departmentmango_rv.setAdapter(departmentmangoAdapter);
        //删除数据
        departmentmangoAdapter.setOnDeleteIconClickListener(new RecySupUserAdapter.OnDeleteIconClickListener() {
            @Override
            public void onDeleteIconClick(int pos) {
                departmentmangoAdapter.removeData(pos);
            }
        });

        crreremot_number_tv.setText("20190213-京-HD-0009");
    }

    /**
     * 初始化控件
     */
    private void initView() {
        //报修编号
        crreremot_number_tv = (TextView) findViewById(R.id.crreremot_number_tv);
        //远程外部
        crreremot_remoteexternal_tv = (TextView) findViewById(R.id.crreremot_remoteexternal_tv);
        crreremot_remoteexternal_ll = (LinearLayout) findViewById(R.id.crreremot_remoteexternal_ll);
        crreremot_remoteexternal_ll.setOnClickListener(this);
        crreremot_remoteexternal_rv = (RecyclerView) findViewById(R.id.crreremot_remoteexternal_rv);//RecyclerView

        crreremot_remoteexternal_rv.setLayoutManager(new GridLayoutManager(this, 2));
        crreremot_remoteexternal_rv.addItemDecoration(new SpaceItemDecoration(8));

        crreremot_pulldown_iv = (ImageView) findViewById(R.id.crreremot_pulldown_iv);
        crreremot_pulldown_iv.setOnClickListener(this);

        //维修换新
        crreremot_maintain_tv = (TextView) findViewById(R.id.crreremot_maintain_tv);
        crreremot_maintain_tv.setOnClickListener(this);
        //部门人员
        crreremot_departmentman_tv = (TextView) findViewById(R.id.crreremot_departmentman_tv);
        crreremot_departmentman_ll = (LinearLayout) findViewById(R.id.crreremot_departmentman_ll);
        crreremot_departmentman_ll.setOnClickListener(this);
        crreremot_departmentman_rv = (RecyclerView) findViewById(R.id.crreremot_departmentman_rv);//RecyclerView
        crreremot_departmentman_rv.setLayoutManager(new GridLayoutManager(this, 2));
        crreremot_departmentman_rv.addItemDecoration(new SpaceItemDecoration(8));
        crreremot_departmentman_iv = (ImageView) findViewById(R.id.crreremot_departmentman_iv);
        crreremot_departmentman_iv.setOnClickListener(this);


        //服务支持
        crreremot_servicesupport_et = (EditText) findViewById(R.id.crreremot_servicesupport_et);
        //项目
        crreremot_project_tv = (TextView) findViewById(R.id.crreremot_project_tv);
        crreremot_project_tv.setOnClickListener(this);
        //质保期
        crreremot_guaranteedate_tv = (TextView) findViewById(R.id.crreremot_guaranteedate_tv);

        //服务安排
        crreremot_arrange_rg = (RadioGroup) findViewById(R.id.crreremot_arrange_rg);
        //不去现场
        crreremot_arrange_rb_no = (RadioButton) findViewById(R.id.crreremot_arrange_rb_no);
        //去现场
        crreremot_arrange_rb_go = (RadioButton) findViewById(R.id.crreremot_arrange_rb_go);

        crreremot_arrange_rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                switch (i){
                    case R.id.crreremot_arrange_rb_no:
                        remote_ll.setVisibility(View.GONE);
                        //1去现场 2不去现场
                        arrange = 2;
                        break;
                    case R.id.crreremot_arrange_rb_go:
                        remote_ll.setVisibility(View.VISIBLE);
                        //1去现场 2不去现场
                        arrange = 1;
                        break;
                }

            }
        });

        //反馈
        crreremot_feedback_ck = (CheckBox) findViewById(R.id.crreremot_feedback_ck);
        //选中监听
        crreremot_feedback_ck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b){//选中
                    feedback = "1";

                }else {//不选中
                    feedback = "2";
                }

            }
        });

        //开始时间
        crreremot_starttime_tv = (TextView) findViewById(R.id.crreremot_starttime_tv);
        crreremot_starttime_tv.setOnClickListener(this);
        //截止时间
        crreremot_stoptime_tv = (TextView) findViewById(R.id.crreremot_stoptime_tv);
        crreremot_stoptime_tv.setOnClickListener(this);
        //车辆
        crreremot_car_et = (EditText) findViewById(R.id.crreremot_car_et);
        //人员
        crreremot_man_tv = (TextView) findViewById(R.id.crreremot_man_tv);
        crreremot_man_ll = (LinearLayout) findViewById(R.id.crreremot_man_ll);
        crreremot_man_ll.setOnClickListener(this);
        crreremot_man_rv = (RecyclerView) findViewById(R.id.crreremot_man_rv);
        crreremot_man_rv.setLayoutManager(new GridLayoutManager(this, 2));
        crreremot_man_rv.addItemDecoration(new SpaceItemDecoration(8));
        crreremot_man_iv = (ImageView) findViewById(R.id.crreremot_man_iv);
        crreremot_man_iv.setOnClickListener(this);


        //现场外部
        crreremot_spotexternal_tv = (TextView) findViewById(R.id.crreremot_spotexternal_tv);
        crreremot_spotexternal_ll = (LinearLayout) findViewById(R.id.crreremot_spotexternal_ll);
        crreremot_spotexternal_ll.setOnClickListener(this);
        crreremot_spotexternal_rv = (RecyclerView) findViewById(R.id.crreremot_spotexternal_rv);
        crreremot_spotexternal_rv.setLayoutManager(new GridLayoutManager(this, 2));
        crreremot_spotexternal_rv.addItemDecoration(new SpaceItemDecoration(8));
        crreremot_spotexternal_iv = (ImageView) findViewById(R.id.crreremot_spotexternal_iv);
        crreremot_spotexternal_iv.setOnClickListener(this);

        //部门人员2
        crreremot_departmentmango_tv = (TextView) findViewById(R.id.crreremot_departmentmango_tv);
        crreremot_departmentmango_ll = (LinearLayout) findViewById(R.id.crreremot_departmentmango_ll);
        crreremot_departmentmango_ll.setOnClickListener(this);
        crreremot_departmentmango_rv = (RecyclerView) findViewById(R.id.crreremot_departmentmango_rv);
        crreremot_departmentmango_rv.setLayoutManager(new GridLayoutManager(this, 2));
        crreremot_departmentmango_rv.addItemDecoration(new SpaceItemDecoration(8));
        crreremot_departmentmango_iv = (ImageView) findViewById(R.id.crreremot_departmentmango_iv);
        crreremot_departmentmango_iv.setOnClickListener(this);
        //备注
        crreremot_remark_et = (EditText) findViewById(R.id.crreremot_remark_et);

        //保存
        crreremot_save_btn = (Button) findViewById(R.id.crreremot_save_btn);
        crreremot_save_btn.setOnClickListener(this);
        //提交
        crreremot_submit_btn = (Button) findViewById(R.id.crreremot_submit_btn);
        crreremot_submit_btn.setOnClickListener(this);
        //结束
        crreremot_end_btn = (Button) findViewById(R.id.crreremot_end_btn);
        crreremot_end_btn.setOnClickListener(this);


        remote_ll = (LinearLayout) findViewById(R.id.remote_ll);//不去现场是隐藏



    }

    /**
     *获取项目
     */
    private void getProInfo() {
        OkHttpUtils.post()
                .url("http://172.16.2.77:9001/api/RepairProcess/GetProInfo")//获取项目
                .addParams("ProjectName", "")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(okhttp3.Call call, Exception e, int id) {
                        Log.i("获取项目请求异常：",e.toString());

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("获取项目请求数据：",response.toString());
                        Gson gson = new Gson();
                        String str = response.toString();
                        ProInfoBean proInfoBean = gson.fromJson(str,ProInfoBean.class);
                        proinfoList = proInfoBean.getObj();
                    }
                });
    }

    /**
     * 获取人员
     */
    private void getUser(){
        OkHttpUtils.get()
                .url("http://172.16.2.77:9001/api/User")//获取人员
                .addParams("RoleID", "60")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(okhttp3.Call call, Exception e, int id) {
                        Log.i("获取人员请求异常：",e.toString());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("获取人员请求数据：",response.toString());
                        Gson gson = new Gson();
                        String str = response.toString();
                        UserBean userBean = gson.fromJson(str,UserBean.class);
                        userlist = userBean.getList();
                    }
         });
    }

    /**
     获取外部部门支持列表
     */
    private void GetSupport(){
        OkHttpUtils.post()
                .url("http://172.16.2.77:9001/api/RepairProcess/GetSupport")//获取外部部门支持列表
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(okhttp3.Call call, Exception e, int id) {
                        Log.i("获取外部部门支持列表请求异常：",e.toString());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("获取外部部门支持列表请求数据：",response.toString());
                        Gson gson = new Gson();
                        String str = response.toString();
                        SupportBean supportBean = gson.fromJson(str,SupportBean.class);
                        supportList = supportBean.getObj();
                        SupportBean.ObjBean objBean = new SupportBean.ObjBean();
                        objBean.setSupportId(999);
                        objBean.setSupportName("无");
                        supportList.add(objBean);
                    }
         });
    }

    /**
     获取外部支持用户
     */
    private void GetSupportUser(int two,boolean flag,String SupportUserIDs) throws IOException {
        MyTask mTask = new MyTask(two,flag,SupportUserIDs);
        mTask.execute();
    }

    /**
     * 根据
     */
    private class MyTask extends AsyncTask<String,Integer,String>{
        private int two;
        private boolean flag;
        private String SupportUserIDs;
        public MyTask(int two,boolean flag,String SupportUserIDs) {//flag 是否是回显  two 1为远程外部人员  2为现场外部人员
            this.two = two;
            this.flag = flag;
            this.SupportUserIDs = SupportUserIDs;
        }
        @Override
        protected String doInBackground(String... strings) {
            JSONObject jsonObject = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            if (two == 1){//远程外部 人员
                for (int i = 0; i < supportList2.size(); i++){
                    if (supportList2.get(i).getSupportId()!= 999){
                        jsonArray.put(supportList2.get(i).getSupportId());
                    }
                }
            }else if (two == 2){//现场外部人员
                for (int i = 0; i < spotexternal.size(); i++){
                    if (spotexternal.get(i).getSupportId()!= 999){
                        jsonArray.put(spotexternal.get(i).getSupportId());
                    }
                }
            }

            try {
                jsonObject.put("SupportIds",jsonArray);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.i("fff",jsonObject.toString());
            String s = jsonObject.toString();
            String k = HttpUtils.doJsonPost("http://172.16.2.77:9001/api/RepairProcess/GetSupportUser", s);
            //Log.i("fsafafda",k);
            return  k;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Log.i("打印：",s);
            if (flag){//true 回显请求
                Gson gson = new Gson();
                if (two == 1){
                    SupportUserBean supportUserBean = gson.fromJson(s,SupportUserBean.class);
                    RemotePeopleList = supportUserBean.getObj();
                    SupportUserBean.ObjBean objBean = new SupportUserBean.ObjBean();
                    List<SupportUserBean.ObjBean.ValueBean> valist = new ArrayList<>();
                    SupportUserBean.ObjBean.ValueBean valueBean1 = new SupportUserBean.ObjBean.ValueBean();
                    valueBean1.setSupportId(999);
                    valueBean1.setSupportName("无");
                    valueBean1.setID(123456);
                    valueBean1.setRealName("无");
                    valist.add(valueBean1);
                    objBean.setKey("无");
                    objBean.setValue(valist);
                    RemotePeopleList.add(objBean);

                    String [] strUserIDs =SupportUserIDs.split(",");
                    //String [] strUserNames =SupportNames.split(",");
                    if (RemotePeopleList != null && RemotePeopleList.size() > 0){
                        for (int k = 0; k < RemotePeopleList.size(); k++){
                            for (int y = 0; y < RemotePeopleList.get(k).getValue().size(); y++){
                                for (int i = 0; i < strUserIDs.length; i++){
                                    if (RemotePeopleList.get(k).getValue().get(y).getID() == Integer.valueOf(strUserIDs[i])){
                                        // 远程外部  人员
                                        SupportUserBean.ObjBean.ValueBean valueBean = new SupportUserBean.ObjBean.ValueBean();
                                        valueBean.setSupportId(RemotePeopleList.get(k).getValue().get(y).getSupportId());
                                        valueBean.setID(RemotePeopleList.get(k).getValue().get(y).getID());
                                        valueBean.setSupportName(RemotePeopleList.get(k).getValue().get(y).getSupportName());
                                        valueBean.setRealName(RemotePeopleList.get(k).getValue().get(y).getRealName());
                                        valueBeanList.add(valueBean );
                                    }
                                }
                            }
                        }
                        crreremot_departmentman_tv.setVisibility(View.GONE);
                        crreremot_departmentman_rv.setVisibility(View.VISIBLE);
                        recySupUserAdapter.notifyDataSetChanged();
                    }
                }else if (two == 2){

                    SupportUserBean supportUserBean = gson.fromJson(s,SupportUserBean.class);
                    SpotPeopleList = supportUserBean.getObj();
                    SupportUserBean.ObjBean objBean = new SupportUserBean.ObjBean();
                    List<SupportUserBean.ObjBean.ValueBean> valist = new ArrayList<>();
                    SupportUserBean.ObjBean.ValueBean valueBean1 = new SupportUserBean.ObjBean.ValueBean();
                    valueBean1.setSupportId(999);
                    valueBean1.setSupportName("无");
                    valueBean1.setID(123456);
                    valueBean1.setRealName("无");
                    valist.add(valueBean1);
                    objBean.setKey("无");
                    objBean.setValue(valist);
                    SpotPeopleList.add(objBean);

                    String [] strUserIDs =SupportUserIDs.split(",");
                    //String [] strUserNames =SupportNames.split(",");
                    if (SpotPeopleList != null && SpotPeopleList.size() > 0){
                        for (int k = 0; k < SpotPeopleList.size(); k++){
                            for (int y = 0; y < SpotPeopleList.get(k).getValue().size(); y++){
                                for (int i = 0; i < strUserIDs.length; i++){
                                    if (SpotPeopleList.get(k).getValue().get(y).getID() == Integer.valueOf(strUserIDs[i])){
                                        // 远程外部  人员
                                        SupportUserBean.ObjBean.ValueBean valueBean = new SupportUserBean.ObjBean.ValueBean();
                                        valueBean.setSupportId(SpotPeopleList.get(k).getValue().get(y).getSupportId());
                                        valueBean.setID(SpotPeopleList.get(k).getValue().get(y).getID());
                                        valueBean.setSupportName(SpotPeopleList.get(k).getValue().get(y).getSupportName());
                                        valueBean.setRealName(SpotPeopleList.get(k).getValue().get(y).getRealName());
                                        departmentmango_valueBeanList.add(valueBean );
                                    }
                                }
                            }
                        }

                        crreremot_departmentmango_tv.setVisibility(View.GONE);
                        crreremot_departmentmango_rv.setVisibility(View.VISIBLE);
                        departmentmangoAdapter.notifyDataSetChanged();
                    }
                }



            }else {
                showDepartmentManPopupWindow(s,two);
            }

        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.crreremot_remoteexternal_ll://远程外部
                showRemoteExternalPopupWindow(1);
                break;
            case R.id.crreremot_pulldown_iv://远程外部
                showRemoteExternalPopupWindow(1);
                break;
            case R.id.crreremot_maintain_tv: //维修换新
                showMaintainPopupWindow(view);
                break;
            case R.id.crreremot_departmentman_ll: //部门人员
                try {
                    GetSupportUser(1,false,null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.crreremot_departmentman_iv:
                try {
                    GetSupportUser(1,false,null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.crreremot_project_tv: //项目
                showProInfoPopupWindow(view);
                break;
            case R.id.crreremot_starttime_tv://开始时间
                DateDialog startDialog = new DateDialog(mContext, startTime, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, final int year, final int monthOfYear, final int dayOfMonth) {
                        TimeDialog timeDialog = new TimeDialog(mContext, startTime, new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                int m = monthOfYear + 1;
                                try {
                                    startTime = DateUtils.getStringTime("yyyy-MM-dd HH:mm", (year + "-" + m + "-" + dayOfMonth + " " + hourOfDay + ":" + minute));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                crreremot_starttime_tv.setText(DateUtils.getFromat("yyyy-MM-dd HH:mm", startTime));
                            }
                        });
                        timeDialog.show();
                    }
                });
                startDialog.show();
                break;
            case R.id.crreremot_stoptime_tv://截止时间
                DateDialog endDialog = new DateDialog(mContext, endTime, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, final int year, final int monthOfYear, final int dayOfMonth) {
                        TimeDialog timeDialog = new TimeDialog(mContext, endTime, new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                int m = monthOfYear + 1;
                                try {
                                    endTime = DateUtils.getStringTime("yyyy-MM-dd HH:mm", (year + "-" + m + "-" + dayOfMonth + " " + hourOfDay + ":" + minute));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                crreremot_stoptime_tv.setText(DateUtils.getFromat("yyyy-MM-dd HH:mm", endTime));
                            }
                        });
                        timeDialog.show();
                    }
                });
                endDialog.show();
                break;
            case R.id.crreremot_man_ll: //人员
                showPersonnelPopupWindow(view);
                break;
            case R.id.crreremot_man_iv: //人员
                showPersonnelPopupWindow(view);
                break;
            case R.id.crreremot_spotexternal_ll:  //现场外部
                showRemoteExternalPopupWindow(2);
                break;
            case R.id.crreremot_spotexternal_iv:  //现场外部
                showRemoteExternalPopupWindow(2);
                break;
            case R.id.crreremot_departmentmango_iv://部门人员2
                try {
                    GetSupportUser(2,false,null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.crreremot_departmentmango_ll://部门人员2
                try {
                    GetSupportUser(2,false,null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;

            case R.id.crreremot_save_btn: //保存
                try {
                    //0保存 1提交
                    remoteSubmit(0);
                } catch (JSONException e) {
                    e.printStackTrace();
                }



                break;
            case R.id.crreremot_submit_btn://提交

                try {
                    //0保存 1提交
                    remoteSubmit(1);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                break;
            case R.id.crreremot_end_btn://结束

                OkHttpUtils.post()
                        .url("http://172.16.2.77:9001/api/RepairProcess/RepairEnd")//结束 远程服务
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(okhttp3.Call call, Exception e, int id) {
                                Log.i("结束 远程服务请求异常：",e.toString());
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                Log.i("结束 远程服务请求数据：",response.toString());
                                Gson gson = new Gson();
                                String str = response.toString();

                            }
                        });
                break;
        }
    }

    /**
     * 提交
     */
    private void remoteSubmit(int state) throws JSONException {
        //报修编号
        String repairnumber = crreremot_number_tv.getText().toString().toString();
        //远程外部 部门
        String SupportNames = "";
        String SupportIDs = "";
        for (int i = 0; i < supportList2.size(); i++){
            /**
             * SupportId : 2
             * SupportName : 研发中心
             */
           // String str = supportList2.get(i).getSupportName();
                    Log.i("提交，远程外部 部门：",supportList2.get(i).getSupportName()+" ,"+supportList2.get(i).getSupportId());
            if (i == supportList2.size() -1){
                SupportNames = SupportNames + supportList2.get(i).getSupportName();
                SupportIDs = SupportIDs + String.valueOf(supportList2.get(i).getSupportId());
            }else {
                SupportNames = SupportNames+supportList2.get(i).getSupportName()+",";
                SupportIDs = SupportIDs+ String.valueOf(supportList2.get(i).getSupportId())+",";
            }

        }
        Log.i("远程外部 部门-->：",SupportNames+" , SupportIDs:"+SupportIDs);

        //维修换新
        String maintain = crreremot_maintain_tv.getText().toString().trim();
        //maintainId; id
        //远程外部 人员
        String SupportUserIDs = "";
        String SupportUserNames = "";
        for (int i = 0; i < valueBeanList.size();i++){
            /**
             * ID : 9
             * RealName : 郑宾
             * SupportId : 1054
             * SupportName : 工程管理中心
             */
            Log.i("提交，远程外部 人员：",valueBeanList.get(i).getRealName()+" ,"+valueBeanList.get(i).getID());

            if (i == valueBeanList.size()-1){
                SupportUserNames = SupportUserNames + valueBeanList.get(i).getRealName();
                SupportUserIDs = SupportUserIDs + valueBeanList.get(i).getID();
            }else {
                SupportUserNames = SupportUserNames + valueBeanList.get(i).getRealName()+",";
                SupportUserIDs = SupportUserIDs + valueBeanList.get(i).getID()+",";
            }
        }
        Log.i("远程外部 人员-->：",SupportUserNames+" , Id:"+SupportUserIDs);


        //服务支持
        String servicesupport = crreremot_servicesupport_et.getText().toString().trim();

        //项目
        String project = crreremot_project_tv.getText().toString().trim();
        //projectId;CYYW18-266
        //projectGuid;022127ed-6edb-4c97-8b9d-fad9758283d7
        //warrantyTime1
        //质保期
        String guaranteedate = crreremot_guaranteedate_tv.getText().toString().trim();

        //服务安排

        //反馈
        //时间
        String starttime = crreremot_starttime_tv.getText().toString().trim();
        String stoptime = crreremot_stoptime_tv.getText().toString().trim();
        //车辆
        String car = crreremot_car_et.getText().toString().trim();

        //人员
        String userIDs = "";
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < userlist2.size(); i++){
            /**
             * UserID : 13
             * UserName : 邢有权
             */
            Log.i("提交,人员：",userlist2.get(i).getUserName()+" ,"+userlist2.get(i).getUserID());
            nextOperatorID = String.valueOf(userlist2.get(0).getUserID());
            if (i == userlist2.size() - 1){
                userIDs = userIDs + String.valueOf(userlist2.get(i).getUserID());
            }else {
                userIDs = userIDs + String.valueOf(userlist2.get(i).getUserID()) + ",";
            }
            jsonArray.put(String.valueOf(userlist2.get(i).getUserID()));



        }
        Log.i("人员-->："," , userIDs:"+userIDs);

        //现场外部 部门
        String Scene_SupportNames = "";
        String Scene_SupportIDs = "";
        for (int i = 0; i < spotexternal.size(); i++){
            Log.i("提交,人员：",spotexternal.get(i).getSupportName()+" ,"+spotexternal.get(i).getSupportId());

            if (i == spotexternal.size() -1){
                Scene_SupportNames = Scene_SupportNames + spotexternal.get(i).getSupportName();
                Scene_SupportIDs = Scene_SupportIDs + spotexternal.get(i).getSupportId();
            }else {
                Scene_SupportNames = Scene_SupportNames + spotexternal.get(i).getSupportName() + ",";
                Scene_SupportIDs = Scene_SupportIDs + spotexternal.get(i).getSupportId() + ",";
            }
        }
        Log.i("现场外部 部门-->：",Scene_SupportNames+" , Id:"+Scene_SupportIDs);
        //现场外部 人员
        String Scene_SupportUserNames = "";
        String Scene_SupportUserIDs = "";
        for (int i = 0; i < departmentmango_valueBeanList.size(); i++){
            Log.i("提交,现场外部 人员：",departmentmango_valueBeanList.get(i).getRealName()+" ,"+departmentmango_valueBeanList.get(i).getID());
            if (i == departmentmango_valueBeanList.size() - 1){
                Scene_SupportUserNames = Scene_SupportUserNames + departmentmango_valueBeanList.get(i).getRealName();
                Scene_SupportUserIDs = Scene_SupportUserIDs + departmentmango_valueBeanList.get(i).getID();
            }else {
                Scene_SupportUserNames = Scene_SupportUserNames + departmentmango_valueBeanList.get(i).getRealName()+ ",";
                Scene_SupportUserIDs = Scene_SupportUserIDs + departmentmango_valueBeanList.get(i).getID()+ ",";
            }
        }
        Log.i("现场外部 人员-->：",Scene_SupportUserNames+" , Id:"+Scene_SupportUserIDs);
        //备注
        String remark = crreremot_remark_et.getText().toString().trim();

        /*{
            "RelationGuid": "string",
                "RepairId": "string",
                "ServiceType": "string",
                "Support": "string",
                "FixUp": 0,
                "Remark": "string",
                "RepairOrChange": 0,
                "Feedback": 0,
                "State": 0,
                "userIDs": [
            0
  ],
            "PlateNumber": "string",
                "SceneTime": "2019-02-19T02:16:12.450Z",
                "EndTime": "2019-02-19T02:16:12.450Z",
                "OperatorID": 0,
                "NextOperatorID": 0,
                "Step": 0,
                "ProjectGuid": "string",
                "SupportUserIDs": "string",
                "SupportUserNames": "string",
                "SupportIDs": "string",
                "SupportNames": "string",
                "Scene_SupportUserIDs": "string",
                "Scene_SupportUserNames": "string",
                "Scene_SupportIDs": "string",
                "Scene_SupportNames": "string",
                "Describe": "string"
        }*/


       /* JSONObject jsonObject = new JSONObject();
        jsonObject.put("RelationGuid","");
        jsonObject.put("RepairId","20190219-京-HD-0015");
        jsonObject.put("ServiceType","");
        jsonObject.put("Support","");
        jsonObject.put("FixUp",arrange);//arrange = 2;//1去现场 2不去现场
        jsonObject.put("Remark",remark);//备注
        jsonObject.put("RepairOrChange",maintainId);//1维修2换新3修和换
        jsonObject.put("Feedback",feedback);// 反馈：  1已以告知报修人安排和费用确认2已处理
        jsonObject.put("State",state);//0保存 1提交
        jsonObject.put("userIDs",jsonArray);// 人员ID
        jsonObject.put("PlateNumber",car);//车牌号
        jsonObject.put("SceneTime",starttime);
        jsonObject.put("EndTime",stoptime);
        jsonObject.put("OperatorID",17);//OperatorID 操作者ID  "UserID": 17,lxq
        jsonObject.put("NextOperatorID",nextOperatorID);//UserID": 18,张孟祥
        jsonObject.put("Step",2);//2
        jsonObject.put("ProjectGuid",projectGuid);
        jsonObject.put("SupportUserIDs",SupportUserIDs);//远程外部 人员ID
        jsonObject.put("SupportUserNames",SupportUserNames);//远程外部 人员名称
        jsonObject.put("SupportIDs",SupportIDs);//远程外部 部门ID
        jsonObject.put("SupportNames",SupportNames);////远程外部 部门名称
        jsonObject.put("Scene_SupportUserIDs",Scene_SupportUserIDs);//现场外部 人员ID
        jsonObject.put("Scene_SupportUserNames",Scene_SupportUserNames);//现场外部 人员名称
        jsonObject.put("Scene_SupportIDs",Scene_SupportIDs);//现场外部 部门Id
        jsonObject.put("Scene_SupportNames",Scene_SupportNames);//现场外部 部门名称
        jsonObject.put("Describe",servicesupport);//服务支持*/


        /*jsonObject.put("ProjectItem",projectId);//项目ID
        jsonObject.put("ProjectLife",warrantyTime1);//项目时间*/




        JSONObject jsonObject = new JSONObject();
        String RelationGuid = null;
        jsonObject.put("RelationGuid",RelationGuid);
        jsonObject.put("RepairId","20190219-京-HD-0015");
        jsonObject.put("ProjectGuid",projectGuid);
        jsonObject.put("Describe",servicesupport);//服务支持
        jsonObject.put("SupportUserIDs",SupportUserIDs);//远程外部 人员ID
        jsonObject.put("SupportIDs",SupportIDs);//远程外部 部门ID
        jsonObject.put("ProjectItem",projectId);//项目ID
        jsonObject.put("ProjectLife",warrantyTime1);//项目时间

        jsonObject.put("FixUp",arrange);//1去现场 2不去现场
        jsonObject.put("userIDs",jsonArray);// 人员ID
        jsonObject.put("PlateNumber",car);//车牌号
        jsonObject.put("SceneTime",starttime);
        jsonObject.put("EndTime",stoptime);
        jsonObject.put("Remark",remark);//备注

        jsonObject.put("RepairOrChange",maintainId);//1维修2换新3修和换
        jsonObject.put("Feedback",feedback);// 反馈：  1已以告知报修人安排和费用确认2已处理
        jsonObject.put("State",state);//0保存 1提交
        jsonObject.put("Step",2);//2
        jsonObject.put("OperatorID",17);//OperatorID 操作者ID  "UserID": 17,lxq
        jsonObject.put("SupportNames",SupportNames);////远程外部 部门名称
        jsonObject.put("SupportUserNames",SupportUserNames);//远程外部 人员名称
        jsonObject.put("Scene_SupportNames",Scene_SupportNames);//现场外部 部门名称
        jsonObject.put("Scene_SupportUserNames",Scene_SupportUserNames);//现场外部 人员名称
        jsonObject.put("Scene_SupportUserIDs",Scene_SupportUserIDs);//现场外部 人员ID
        jsonObject.put("NextOperatorID",nextOperatorID);//UserID": 18,张孟祥   不去现场是 17 自己
        jsonObject.put("Scene_SupportIDs",Scene_SupportIDs);//现场外部 部门Id



    /*    {
            "RelationGuid": "",
                "RepairId": "20190219-京-HD-0015",
                "ProjectGuid": "022127ed-6edb-4c97-8b9d-fad9758283d7",
                "Describe": "服务支持",
                "SupportUserIDs": "27,1008",
                "SupportIDs": "2,41",
                "ProjectItem": "CYYW18-266",
                "ProjectLife": "2018-12-31T00:00:00",
                "FixUp": 1,
                "userIDs": [
            18,
                    14
  ],
            "PlateNumber": "京",
                "SceneTime": "2019-02-19 11:07",
                "EndTime": "2019-02-19 11:07",
                "Remark": "备注",
                "RepairOrChange": "1",
                "Feedback": 1,
                "State": 1,
                "Step": 2,
                "OperatorID": 17,
                "SupportNames": "研发中心,技术中心",
                "SupportUserNames": "张守伟,赵娜娜",
                "Scene_SupportNames": "研发中心,技术中心",
                "Scene_SupportUserNames": "张守伟,赵娜娜",
                "Scene_SupportUserIDs": "27,1008",
                "NextOperatorID": "14",
                "Scene_SupportIDs": "2,41"
        }*/
/*        {RelationGuid: null, RepairId: "20190219-京-CY-0048",…}
        Describe: "fff"
        EndTime: "2019-02-20 17:30"
        Feedback: 1
        FixUp: 1
        NextOperatorID: "18"
        OperatorID: 17
        PlateNumber: "fff"
        ProjectGuid: "022127ed-6edb-4c97-8b9d-fad9758283d7"
        ProjectItem: "CYYW18-266"
        ProjectLife: "2018-12-31 00-00"
        RelationGuid: null
        Remark: "bb"
        RepairId: "20190219-京-CY-0048"
        RepairOrChange: 1
        SceneTime: "2019-02-20 08:30"
        Scene_SupportIDs: "2,41"
        Scene_SupportNames: "研发中心,技术中心"
        Scene_SupportUserIDs: "2013,2012"
        Scene_SupportUserNames: "张学,李学胜"
        State: 1
        Step: 2
        SupportIDs: "41,2"
        SupportNames: "研发中心,技术中心"
        SupportUserIDs: "27,1008"
        SupportUserNames: "张守伟,赵娜娜"
        SupportUsers1: [27, 1008]
        SupportUsers2: [2013, 2012]
        Supports1: [41, 2]
        Supports2: [2, 41]
        userIDs: ["18", "19"]
        0: "18"
        1: "19"*/

        /*JSONObject jsonObject = new JSONObject();
        jsonObject.put("RelationGuid","");
        jsonObject.put("RepairId","20190219-京-HD-0015");
        jsonObject.put("ProjectGuid",projectGuid);
        jsonObject.put("Describe",servicesupport);//服务支持
        //jsonObject.put("SupportUsers1",);
        jsonObject.put("SupportUserIDs",SupportUserIDs);//远程外部 人员ID

        //jsonObject.put("Supports1","");
        //jsonObject.put("Supports2",);
        jsonObject.put("SupportIDs",SupportIDs);//远程外部 部门ID
        //jsonObject.put("SupportUsers2",);
        jsonObject.put("ProjectItem",projectId);//项目ID
        jsonObject.put("ProjectLife",warrantyTime1);//项目时间

        jsonObject.put("FixUp",arrange);//arrange = 2;//1去现场 2不去现场
        jsonObject.put("userIDs",jsonArray);// 人员ID
        jsonObject.put("PlateNumber",car);//车牌号
        jsonObject.put("SceneTime",starttime);
        jsonObject.put("EndTime",stoptime);
        jsonObject.put("Remark",remark);//备注

        jsonObject.put("RepairOrChange",maintainId);//1维修2换新3修和换
        jsonObject.put("Feedback",feedback);// 反馈：  1已以告知报修人安排和费用确认2已处理
        jsonObject.put("State",state);//0保存 1提交
        jsonObject.put("Step",2);//2
        jsonObject.put("OperatorID",17);//OperatorID 操作者ID  "UserID": 17,lxq
        jsonObject.put("SupportNames",SupportNames);////远程外部 部门名称
        jsonObject.put("SupportUserNames",SupportUserNames);//远程外部 人员名称
        jsonObject.put("Scene_SupportNames",Scene_SupportNames);//现场外部 部门名称
        jsonObject.put("Scene_SupportUserNames",Scene_SupportUserNames);//现场外部 人员名称
        jsonObject.put("Scene_SupportUserIDs",Scene_SupportUserIDs);//现场外部 人员ID
        jsonObject.put("NextOperatorID",nextOperatorID);//UserID": 18,张孟祥
        jsonObject.put("Scene_SupportIDs",Scene_SupportIDs);//现场外部 部门Id*/


        Log.i("fff",jsonObject.toString());

        String strjson = jsonObject.toString();
       /* MySubmitTask mTask = new MySubmitTask(strjson);
        mTask.execute();*/
    }


    private class MySubmitTask extends AsyncTask<String,Integer,String>{
        private String strjson;
        public MySubmitTask(String strjson) {
            this.strjson = strjson;
        }
        @Override
        protected String doInBackground(String... strings) {

            String k = HttpUtils.doJsonPost("http://172.16.2.77:9001/api/RepairProcess/AddOrUpdateRemote", strjson);
            Log.i("fsafafda",k);

            return  k;
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Log.i("打印是否提交成功：",s);

        }
    }

    /**
     * 保存
     */
    private void remoteSave() {
    }

    /**
     保存 远程服务
     */
    private void AddOrUpdateRemote (){
       /* {
            "RelationGuid": "string",
                "RepairId": "string",
                "ServiceType": "string",
                "Support": "string",
                "FixUp": 0,
                "Remark": "string",
                "RepairOrChange": 0,
                "Feedback": 0,
                "State": 0,
                "userIDs": [
            0
  ],
            "PlateNumber": "string",
                "SceneTime": "2019-02-15T09:11:14.488Z",
                "EndTime": "2019-02-15T09:11:14.488Z",
                "OperatorID": 0,
                "NextOperatorID": 0,
                "Step": 0,
                "ProjectGuid": "string",
                "SupportUserIDs": "string",
                "SupportUserNames": "string",
                "SupportIDs": "string",
                "SupportNames": "string",
                "Scene_SupportUserIDs": "string",
                "Scene_SupportUserNames": "string",
                "Scene_SupportIDs": "string",
                "Scene_SupportNames": "string",
                "Describe": "string"
        }*/

       // {"RelationGuid":null,"RepairId":"20190214-京-CY-0038","ProjectGuid":"5d9890a8-eb56-49cb-ae28-64242d3292b6","Describe":"111",
        // "SupportUsers1":[1008,2011,2013],"SupportUserIDs":"1008,2011,2013","Supports1":[2,41],"Supports2":[2,41,1052,1053],
        // "SupportIDs":"2,41","SupportUsers2":[27,1008,2011,2012],"ProjectItem":"15029","ProjectLife":"2016-06-22 00-00",
        // "FixUp":1,"userIDs":["18","16","14"],"PlateNumber":"11","SceneTime":"2019-02-16 08:30",
        // "EndTime":"2019-02-16 17:30","Remark":"22222","RepairOrChange":1,"Feedback":"1","State":1,"Step":2,"OperatorID":17,
        // "SupportNames":"研发中心,技术中心","SupportUserNames":"赵娜娜,邓绪华,李学胜","Scene_SupportNames":"研发中心,技术中心,综管中心,市场中心",
        // "Scene_SupportUserNames":"张守伟,赵娜娜,邓绪华,张学","Scene_SupportUserIDs":"27,1008,2011,2012","NextOperatorID":"18","Scene_SupportIDs":"2,41,1052,1053"}

        OkHttpUtils.post()
                .url("http://172.16.2.77:9001/api/RepairProcess/AddOrUpdateRemote")//保存 远程服务
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(okhttp3.Call call, Exception e, int id) {
                        Log.i("获取外部部门支持列表请求异常：",e.toString());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("获取外部部门支持列表请求数据：",response.toString());
                        Gson gson = new Gson();
                        String str = response.toString();
                        SupportBean supportBean = gson.fromJson(str,SupportBean.class);
                        supportList = supportBean.getObj();
                    }
                });


    }

    /**
     * 弹出 人员 集合
     * @param view
     */
    private void showPersonnelPopupWindow(View view) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.region_popwindow, null);
        //contentView.setBackgroundColor(Color.WHITE);
        contentView.setBackgroundResource(R.drawable.edittext_bg);
        // 设置按钮的点击事件
        ListView listview = (ListView) contentView.findViewById(R.id.region_pop_listview);

        PersonnelAdapter adapter = new PersonnelAdapter(mContext,userlist,userisselected,userlist2);

        //final PopupWindow popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        //final PopupWindow popupWindow = new PopupWindow(contentView, 500, 300, true);
        final PopupWindow popupWindow = new PopupWindow(contentView, crreremot_man_ll.getWidth(), 600, true);
        listview.setAdapter(adapter);
        popupWindow.setTouchable(true);

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                Log.i("mengdd", "onTouch : ");

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });

        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        //popupWindow.setBackgroundDrawable(getResources().getDrawable(Color.BLACK));
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
        // 设置好参数之后再show
        popupWindow.showAsDropDown(crreremot_man_ll);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {



            }
        });

    }


    /**
     * 弹出Popwindow  远程外部 部门集合
     *
     */
    private void showRemoteExternalPopupWindow(int one) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.region_popwindow, null);
        //contentView.setBackgroundColor(Color.WHITE);
        contentView.setBackgroundResource(R.drawable.edittext_bg);
        // 设置按钮的点击事件
        ListView listview = (ListView) contentView.findViewById(R.id.region_pop_listview);
        SupportAdapter adapter = null;
        if (one == 1){//远程外部
            adapter = new SupportAdapter(mContext,supportList,isselected,supportList2,one);
        }else if (one == 2){//现场外部
            adapter = new SupportAdapter(mContext,supportList,spotexternal_isselected,spotexternal,one);
        }


        //final PopupWindow popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        //final PopupWindow popupWindow = new PopupWindow(contentView, 500, 300, true);
        PopupWindow popupWindow = null;
        if (one == 1){//远程外部
            popupWindow = new PopupWindow(contentView, crreremot_remoteexternal_ll.getWidth(), 600, true);
        }else if (one == 2){//现场外部
            popupWindow = new PopupWindow(contentView, crreremot_spotexternal_ll.getWidth(), 600, true);
        }

        listview.setAdapter(adapter);
        popupWindow.setTouchable(true);

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                Log.i("mengdd", "onTouch : ");

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });

        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        //popupWindow.setBackgroundDrawable(getResources().getDrawable(Color.BLACK));
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
        // 设置好参数之后再show
        if (one == 1){//远程外部
            popupWindow.showAsDropDown(crreremot_remoteexternal_ll);
        }else if (one == 2){//现场外部
            popupWindow.showAsDropDown(crreremot_spotexternal_ll);
        }

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {



            }
        });
    }

    /**
     * 弹出Popwindow  部门人员 人员集合
     * @param
     */
    private void showDepartmentManPopupWindow(String json,int two) {
        Gson gson = new Gson();
        SupportUserBean supportUserBean = gson.fromJson(json,SupportUserBean.class);
        List<SupportUserBean.ObjBean> objBeanList = supportUserBean.getObj();
        SupportUserBean.ObjBean objBean = new SupportUserBean.ObjBean();
        List<SupportUserBean.ObjBean.ValueBean> valist = new ArrayList<>();
        SupportUserBean.ObjBean.ValueBean valueBean = new SupportUserBean.ObjBean.ValueBean();
        valueBean.setSupportId(999);
        valueBean.setSupportName("无");
        valueBean.setID(123456);
        valueBean.setRealName("无");
        valist.add(valueBean);
        objBean.setKey("无");
        objBean.setValue(valist);
        objBeanList.add(objBean);


        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.departmentman_popwindow, null);
        //contentView.setBackgroundColor(Color.WHITE);
        contentView.setBackgroundResource(R.drawable.edittext_bg);
        // 设置按钮的点击事件
        ExpandableListView listview = (ExpandableListView) contentView.findViewById(R.id.expandableListView);
        DepManExpandAdapter adapter = null;
        if (two == 1){
            adapter = new DepManExpandAdapter(mContext,objBeanList,supportuserisselected,valueBeanList,two);
        }else if (two == 2){
            adapter = new DepManExpandAdapter(mContext,objBeanList,departmentmango_isselected,departmentmango_valueBeanList,two);
        }

        //SupportUserOneAdapter adapter = new SupportUserOneAdapter(mContext,objBeanList,supportuserisselected,valueBeanList);

        //final PopupWindow popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        //final PopupWindow popupWindow = new PopupWindow(contentView, 500, 300, true);
        PopupWindow popupWindow =null;
        if (two == 1){
            popupWindow = new PopupWindow(contentView, crreremot_departmentman_ll.getWidth(), 600, true);
        }else if (two == 2){
            popupWindow = new PopupWindow(contentView, crreremot_departmentmango_ll.getWidth(), 600, true);
        }

        listview.setAdapter(adapter);
        popupWindow.setTouchable(true);


        listview.setGroupIndicator(null);//这个是设定每个Group之前的那个图标
        /*//点击二级列表的监听
        expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
             @Override
             public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                 TextView childAt = (TextView)((LinearLayout) v).getChildAt(1);//获得点击列表中TextView的值，需要强转一下，否则找不到getChildAt方法
                 Toast.makeText(Main2Activity.this, "点击了 "+childAt.getText()+" 列表", Toast.LENGTH_SHORT).show();
                return true;
              }

        });*/

        //设置默认展开
        for(int i = 0; i < adapter.getGroupCount(); i++){
            listview.expandGroup(i);
        }
        //设置一级不可点击
        listview.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {

                //设置点击不关闭（不收回）
                view.setClickable(true);
                return true;
                //return false;
            }
        });

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Log.i("mengdd", "onTouch : ");
                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });

        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        //popupWindow.setBackgroundDrawable(getResources().getDrawable(Color.BLACK));
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
        // 设置好参数之后再show
        if (two == 1){//远程外部 人员
            popupWindow.showAsDropDown(crreremot_departmentman_ll);
        }else if(two == 2){//现场外部 人员
            popupWindow.showAsDropDown(crreremot_departmentmango_ll);
        }

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            }
        });
    }


    /**
     * 弹出Popwindow  维修换新
     * @param view
     */
    private void showMaintainPopupWindow(View view) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.region_popwindow, null);
        //contentView.setBackgroundColor(Color.WHITE);
        contentView.setBackgroundResource(R.drawable.edittext_bg);
        // 设置按钮的点击事件
        ListView listview = (ListView) contentView.findViewById(R.id.region_pop_listview);
        MaintainAdapter adapter = new MaintainAdapter(mContext,maintainList);

        //final PopupWindow popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        //final PopupWindow popupWindow = new PopupWindow(contentView, 500, 300, true);
        final PopupWindow popupWindow = new PopupWindow(contentView, crreremot_maintain_tv.getWidth(), 400, true);
        listview.setAdapter(adapter);
        popupWindow.setTouchable(true);

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                Log.i("mengdd", "onTouch : ");

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });

        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        //popupWindow.setBackgroundDrawable(getResources().getDrawable(Color.BLACK));
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
        // 设置好参数之后再show
        popupWindow.showAsDropDown(view);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                crreremot_maintain_tv.setText(maintainList.get(i).getLabel());
                maintainId = maintainList.get(i).getValue();
                //关闭popwindow
                popupWindow.dismiss();

            }
        });
    }

    /**
     * 弹出Popwindow  项目集合
     * @param view
     */
    private void showProInfoPopupWindow(View view) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.region_popwindow, null);
        //contentView.setBackgroundColor(Color.WHITE);
        contentView.setBackgroundResource(R.drawable.edittext_bg);
        // 设置按钮的点击事件
        ListView listview = (ListView) contentView.findViewById(R.id.region_pop_listview);
        ProInfoAdapter adapter = new ProInfoAdapter(mContext,proinfoList);

        //final PopupWindow popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        //final PopupWindow popupWindow = new PopupWindow(contentView, 500, 300, true);
        final PopupWindow popupWindow = new PopupWindow(contentView, crreremot_project_tv.getWidth(), 600, true);
        listview.setAdapter(adapter);
        popupWindow.setTouchable(true);

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                Log.i("mengdd", "onTouch : ");

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });

        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        //popupWindow.setBackgroundDrawable(getResources().getDrawable(Color.BLACK));
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
        // 设置好参数之后再show
        popupWindow.showAsDropDown(view);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                crreremot_project_tv.setText(proinfoList.get(i).getProjectName());
                projectId = proinfoList.get(i).getProjectId();//项目ID
                projectGuid = proinfoList.get(i).getProjectGuid();
                //warrantyTime1 = proinfoList.get(i).getWarrantyTime();//时间
               // String time = warrantyTime1.replace("T"," ");


                String WarrantyTime = proinfoList.get(i).getWarrantyTime();
                warrantyTime1 = WarrantyTime.subSequence(0,10)+" 00-00";
                Log.i("项目：",proinfoList.get(i).getProjectName()+" ,Id:"+projectId+" ,projectGuid:"+projectGuid+",:"+warrantyTime1);
                crreremot_guaranteedate_tv.setText(warrantyTime1);
                //crreremot_guaranteedate_tv.setText(time);
                popupWindow.dismiss();


            }
        });
    }
}
